$(function () {

    initGridData();

    initEvent();

});

function initGridData(formData) {
    $.ajax({
        url: 'report_orderReport',
        type: 'post',
        data: formData,
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                var data = result.data;
                $('#grid').datagrid({
                    data: data,
                    columns: [[
                        {field: 'name', title: '商品类型', width: 100},
                        {field: 'money', title: '销售额', width: 100}
                    ]],
                    singleSelect: true,
                    onLoadSuccess: function (data) {
                        //显示图
                        showChart(data.rows);
                    }
                });
            } else {
                $.messager.alert("提示", result.message, 'info', null);
            }
        }
    })
}


function initEvent() {
    $('#btnSearch').bind('click', function () {
        var formdata = $('#searchForm').serializeJSON();
        if (formdata.endDate) {
            formdata.endDate += " 23:59:59";
        }
        initGridData(formdata);
    });
}


//显示图
function showChart(data) {
    if (!data || !data.length) {
        return;
    }
    var pieData = [];
    $.each(data, function (i, item) {
        if (i === 0) {
            pieData.push({name: item.name, y: item.money, sliced: true, selected: true});
        } else {
            pieData.push({name: item.name, y: item.money});
        }
    });

    $('#pieChart').highcharts({
        chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'
        },
        title: {
            text: '销售统计'
        },
        //信用
        credits: {enabled: false},
        //导出
        exporting: {enabled: true},
        tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
        },
        plotOptions: {
            pie: {
                allowPointSelect: true,
                cursor: 'pointer',
                dataLabels: {
                    enabled: true
                },
                showInLegend: true
            }
        },
        series: [{
            name: "比例",
            colorByPoint: true,
            data: pieData
        }]
    });
}